package com.elcom.roaming.common.config;

import java.io.File;

import org.jconfig.Configuration;
import org.jconfig.ConfigurationManager;
import org.jconfig.ConfigurationManagerException;
import org.jconfig.handler.XMLFileHandler;

public abstract class ConfigInit {
	private Configuration config;
	protected String configFolder;
	protected String configFile;
	
	
	public ConfigInit(String configFolder, String configFile) {
		this.configFolder = configFolder;
		this.configFile = configFile;
		firstLoadConfig();
		reloadConfig();
	}

	private void firstLoadConfig(){
		ConfigurationManager cm = ConfigurationManager.getInstance();
        try {
            File file = new File(configFolder);
            if (!file.exists()) {
                file.mkdirs();
            }
            
            file = new File(configFile);
            if (!file.exists()) {
                createDefaultConfigFile();
            }
            
            XMLFileHandler fileHandler = new XMLFileHandler();
            fileHandler.setFile(file);
            cm.load(fileHandler, configFile);
        } catch (ConfigurationManagerException cme1) {
        	onError(cme1);
        }
	}
	
	protected abstract void createDefaultConfigFile();
	
	protected abstract void onError(Exception e);
	
	public Configuration getConfig(){
		return config;
	}

	public void reloadConfig() {
		config = ConfigurationManager.getConfiguration(configFile);
	}
}
